package com.simple.gateway.pay.utils;


import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;

import java.util.Arrays;
import java.util.Map;

@Slf4j
public class SignUtil {

    public static String createSign(Map<String, Object> body, String serviceKey, String orderNo, String flag) {
        String data = createLinkString(body) + serviceKey;
        log.info("商户号【{}】" + flag + "==>>{},代签名串==>>{}", orderNo, "签名中", data);
        String sign = Cryptos.generateSha256(data);
        log.info("商户号【{}】" + flag + "==>>{},签名结果==>>{}", orderNo, "签名中", sign);
        return sign;
    }


    public static boolean verifySign(Map<String, Object> object, String serviceKey, String sign, String orderNo, String flag) {
        String newSign = createSign(object, serviceKey, orderNo, flag);
        if (newSign.equals(sign)) {
            log.info("商户号【{}】请求处理==>>{},结果==>>{}", orderNo, "验签中", "验签成功");
            return true;
        } else {
            log.info("商户号【{}】请求处理==>>{},结果==>>{}", orderNo, "验签中", "验签失败");
            return false;
        }
    }

    public static String createLinkString(Map<String, Object> params) {
        Object[] keys = params.keySet().toArray();
        Arrays.sort(keys);
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < keys.length; i++) {
            if (!StringUtils.isEmpty(params.get(keys[i]))) {
                sb.append(keys[i]).append("=").append(params.get(keys[i]));
                if (i != keys.length - 1) sb.append("&");
            }
        }
        if (sb.toString().endsWith("&")) {
            return sb.deleteCharAt(sb.length() - 1).toString();
        }
        return sb.toString();
    }
}
